<template lang="pug">
.cp-encode-rule-popup
  el-dialog.rule-pop(
    title="规则设置",
    :visible="visible",
    @close="closeDialog",
    width="60%")
    .table-title
      span 预览：{{preview}}
    el-table(
      :data="tableList",
      height="400px",
      highlight-current-row,
      v-loading="loadingTable",
      size="mini",
      border)
      el-table-column(align="center", type="index", label="序号")
      el-table-column(align="center", label="位数")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit") {{scope.row.digits}}
          div(v-show="scope.row.canEdit")
            el-input(v-model="scope.row.digits")
      el-table-column(align="center", label="数据来源", min-width="160px")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit") {{scope.row.datasourceId | getText(dataSource)}}
          div(v-show="scope.row.canEdit")
            el-select(v-model="scope.row.datasourceId", placeholder="请选择")
              el-option(
                v-for="(item, index) in dataSource",
                :key="index",
                :label="item.name",
                :value="item.id")
      el-table-column(align="center", label="固定值", min-width="120px")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit && scope.row.datasourceId==='fv'") {{scope.row.constant}}
          div(v-show="scope.row.canEdit && scope.row.datasourceId==='fv'")
            el-input(v-model="scope.row.constant")
      el-table-column(align="center", label="起始值")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit && scope.row.datasourceId==='sn'") {{scope.row.snBeginning}}
          div(v-show="scope.row.canEdit && scope.row.datasourceId==='sn'")
            el-input(v-model="scope.row.snBeginning")
      el-table-column(align="center", label="截止值")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit && scope.row.datasourceId==='sn'") {{scope.row.snEnding}}
          div(v-show="scope.row.canEdit && scope.row.datasourceId==='sn'")
            el-input(v-model="scope.row.snEnding")
      el-table-column(align="center", label="步长")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit && scope.row.datasourceId==='sn'") {{scope.row.snStep}}
          div(v-show="scope.row.canEdit && scope.row.datasourceId==='sn'")
            el-input(v-model="scope.row.snStep")
      el-table-column(align="center", label="重置")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit && scope.row.datasourceId==='sn'") {{scope.row.snCircular | getText(snCircularList)}}
          div(v-show="scope.row.canEdit && scope.row.datasourceId==='sn'")
            el-select(v-model="scope.row.snCircular", placeholder="请选择")
              el-option(
                v-for="(item, index) in snCircularList",
                :key="index",
                :label="item.name",
                :value="item.id")
      el-table-column(align="center", label="操作", min-width="96px")
        template(slot-scope="scope")
          div(v-show="!scope.row.canEdit")
            i.icon-act.el-icon-edit(@click="editItem(scope.$index, scope.row)")
            i.icon-act.el-icon-plus(@click="addItem(scope.$index, scope.row)")
            i.icon-act.el-icon-delete(@click="deleteItem(scope.$index, scope.row)")
          div(v-show="scope.row.canEdit")
            i.icon-act.el-icon-check(@click="saveEditItem(scope.$index, scope.row)")
            i.icon-act.el-icon-close(@click="cancelEditItem(scope.$index, scope.row)")
    .dialog-footer(slot="footer")
      el-button(type="primary", plain, @click="closeDialog") 取消
      el-button(type="primary", @click="saveData") 保存
</template>

<script>
import ConfigApi from '@/api/config';

export default {
  name: 'encoderule',
  props: {
    visible: Boolean,
    parentData: Object
  },
  data() {
    return {
      loadingTable: false,
      tableList: [{ canEdit: false }],
      dataSource: [],
      // 重置下拉框的选项
      snCircularList: [
        { id: 0, name: 'NO' },
        { id: 1, name: 'YES' }
      ],
    };
  },
  filters: {
    // 根据下拉框选项获取文本
    getText(id, list) {
      const target = list.find(item => item.id === id);
      if (target) {
        return target.name;
      }
      return null;
    },
  },
  computed: {
    preview() {
      const text = '';
      return text;
    }
  },
  watch: {
    parentData(newData, oldData) {
      if (newData !== oldData) {
        if (newData.tableList) {
          this.tableList = newData.tableList;
        }
        this.dataCache = [];
      }
    }
  },
  created() {
    this.getDataSource();
  },
  methods: {
    // 数据来源列表
    getDataSource() {
      ConfigApi.getCodeDataSource({ coder: '00000008' }).then((res) => {
        if (!res.status && res.obj) {
          this.dataSource = res.obj.dataSources;
        }
      });
    },
    // 关闭、取消
    closeDialog() {
      this.$emit('close');
    },
    // 验证输入数据
    validateParam(data = []) {
      let needDigits = false;
      let needDataSource = false;
      let needSave = false;
      data.forEach((item) => {
        if (item.canEdit) {
          needSave = true;
        }
        if (!item.digits && item.digits !== 0) {
          needDigits = true;
        }
        if (!item.datasourceId && item.datasourceId !== 0) {
          needDataSource = true;
        }
      });
      return {
        needSave,
        needDigits,
        needDataSource
      };
    },
    // 保存
    saveData() {
      const { needSave, needDigits, needDataSource } = this.validateParam(this.tableList);
      if (needDigits) {
        this.$message({ message: '请输入位数', type: 'warning' });
        return;
      }
      if (needDataSource) {
        this.$message({ message: '请选择数据来源', type: 'warning' });
        return;
      }
      if (needSave) {
        this.$message({ message: '请先保存编辑', type: 'warning' });
        return;
      }
      this.loadingTable = true;
      const params = { coder: this.firstType, encodingRecords: this.tableList };
      ConfigApi.submitConCodeDetail(params).then((res) => {
        if (res.status === 0) {
          this.$message({ message: '保存成功', type: 'success' });
          this.loadingTable = false;
          this.$emit('submit', params);
          this.closeDialog();
        } else {
          this.loadingTable = false;
          this.$message.error(res.comment || '保存失败');
        }
      }).catch((error) => {
        this.loadingTable = false;
        console.log(JSON.stringify(error));
      });
    },
    /* ****** 表格操作  ****** */
    // 编辑
    editItem(index) {
      this.dataCache[index] = Object.assign({}, this.tableList[index]);
      this.$set(this.tableList[index], 'canEdit', true);
    },
    // 新增
    addItem(index) {
      this.tableList.splice((index + 1), 0, { state: 0, canEdit: true });
      this.dataCache.splice((index + 1), 0, { state: 0, canEdit: true, fromAdd: true });
    },
    // 删除
    deleteItem(index) {
      if (this.tableList.length < 2) return;
      this.tableList.splice(index, 1);
    },
    // 保存
    saveEditItem(index) {
      this.tableList[index].canEdit = false;
    },
    // 取消
    cancelEditItem(index) {
      const cache = Object.assign({}, this.dataCache[index], { canEdit: false });
      if (cache.fromAdd) {
        // 新增时取消
        this.tableList.splice(index, 1);
        this.dataCache.splice(index, 1);
      } else {
        // 编辑时取消
        this.tableList.splice(index, 1, cache);
        this.tableList[index].canEdit = false;
      }
    }
  }
};
</script>

<style lang="sass">
.cp-encode-rule-popup
  .el-table
    th, td
      text-align: center
  .rule-pop
    &::-webkit-scrollbar
      display: none
    .el-dialog
      margin-top: 5vh!important
    .el-dialog__body
      padding-top: 10px
    .el-dialog__footer
      text-align: center
      padding-top: 0
      .el-button
        width: 80px
  .table-title
    margin: 0 0 10px 0
  .rule-pop-table
    .icon-act
      font-size: 16px
      font-weight: 500
      padding: 4px
      cursor: pointer
      &:hover
        color: #5D9BFB
</style>
